package com.yn.demo_redis_lock.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RedisPool
 * @Description:
 * @author: 王胜
 * @date 2021/4/12
 * @Version: 1.0
 **/
@Component
public class RedisPool {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
       * 上锁
       * 将键值对设定一个指定的时间timeout.
       *
       * @param key
       * @param timeout 键值对缓存的时间，单位是秒
       * @return 设置成功返回true，否则返回false
       */
  public boolean tryLock(String key, String value, long timeout) {
      if (StringUtils.isEmpty(key)) {
          return false;
      }
    //底层原理就是Redis的setnx方法
    boolean isSuccess = redisTemplate.opsForValue().setIfAbsent(key, value);
    return isSuccess;
  }

    public String get(String key) {
            return (String)redisTemplate.opsForValue().get(key);
    }
    public void setList(String key) {
        ListOperations<String,String> listOperations = redisTemplate.opsForList();
        listOperations.leftPush(key,"9192");
        listOperations.leftPush(key,"9191");
        listOperations.leftPush(key,"9193");
    }
    public List<String> getList(String key) {
        ListOperations<String,String> listOperations = redisTemplate.opsForList();
        return listOperations.range(key,0,-1);
    }
    public void set(String key,Integer i) {
        redisTemplate.opsForValue().set(key,i.toString());
    }

    /**
     * 释放锁
     */
    public void releaseLock(String key) {
        if (!StringUtils.isEmpty(key)) {
            redisTemplate.delete(key);
        }
    }
}
